
import INTERFACE from './namespace'

import store from '../store/index.js'

import {toast, showLoading, hideLoading} from './utils'

const JSONbigString = require('json-bigint')({ storeAsString: true })


function handleResult (resolve,reject,result,error,row) {
  // 成功
  const isSuccess = result.statusCode === 200 && result.data && result.data.code === 200

  // 过期
  const isExpired = result.statusCode === 200 && result.data && result.data.code === 30007 

  const isError = result.statusCode !== 200 || !isSuccess
  if (result.errMsg === 'request:fail 超时') {
    return toast('请求超时')
  }
  if (isError) {
    const errMsg = result.data ? result.data.msg : '服务异常'
    if (error) {
      // 手动处理
      console.log('手动处理错误')
      reject(result.data)
    } else {
      toast(errMsg)
    }
  } 
  if (isSuccess) {
		let res
		if (row) {
			// 返回原始相应数据
			res = result.data
		} else {
			res = result.data.data
		}
    resolve(res)
  }
}

export default function request (url, options = {}) {
  if (url.includes('/')) {
    // url包含拼接的参数
    const index = url.indexOf('/')
    const path = url.substring(0, index)
    const left = url.substring(index)
    url = INTERFACE[path] + left
  } else {
    url = INTERFACE[url]
  }
  let { data = {}, method = 'get', header = {}, loading = true, error = false, withoutToken=false,
row=false} = options
   if (!withoutToken) header.Authorization = `Bearer ${store.state.token}`
	 
  return new Promise((resolve, reject) => {
    loading && showLoading()
    uni.request({
      url,
      method,
      header,
      data,
			dataType: 'text',
      success: (result) => {
        loading && hideLoading()
				result.data = JSONbigString.parse(result.data)
        handleResult(resolve, reject, result, error, row)
      }
    })
  })
}
